import { useState } from "react";
import { CloseOutlined } from "@ant-design/icons";
import { Button, Drawer, Flex, type FormInstance } from "antd";
import type { Values } from "../types";
import EditForm from "./edit-form";
import { createOrder, updateOrder } from "@/api";

type EditModalProps = {
  open: boolean;
  onCreate: (values: Values) => Promise<unknown>;
  onCancel: () => void;
  initialValues?: Values;
};

export default function EditModal({ open, onCreate, onCancel, initialValues }: EditModalProps) {
  const [formInstance, setFormInstance] = useState<FormInstance>();
  const [loading, setLoading] = useState(false);
  return (
    <Drawer
      open={open}
      destroyOnClose
      maskClosable={false}
      loading={loading}
      closable={false}
      width={640}
      title={
        <>
          <Flex justify="space-between" align="center">
            <div>
              <span className="text-l font-bold">{initialValues ? "编辑" : "新建"}商单</span>
            </div>
            <Button icon={<CloseOutlined />} type="text" size="small" onClick={() => onCancel()}></Button>
          </Flex>
        </>
      }
    >
      <EditForm
        initialValues={initialValues}
        onFormInstanceReady={(form) => {
          setFormInstance(form);
        }}
        onSubmit={async () => {
          try {
            const values = await formInstance?.validateFields();
            const data = {
              ...values,
              cooperationStart: values.cooperationDate[0],
              cooperationEnd: values.cooperationDate[1],
            };
            setLoading(true);
            onCreate(data).finally(async () => {
              try {
                if (initialValues) {
                  await updateOrder(initialValues.id, data);
                } else {
                  await createOrder(data);
                }
                onCancel();
              } catch (error) {
                console.log("Failed:", error);
              } finally {
                setLoading(false);
              }
            });
          } catch (error) {
            console.log("Failed:", error);
          }
        }}
        onReset={() => {
          // formInstance?.resetFields();
        }}
      />
    </Drawer>
  );
}
